package com.pb.news.web.servlet;

import com.pb.news.dao.NewsDao;
import com.pb.news.dao.impl.NewsDaoImpl;
import com.pb.news.entity.News;
import com.pb.news.service.impl.NewsServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * ${NAME}--BDQN_WEB_NEWS
 *
 * @author: Jovi
 * @createTime: 2018-04-11 11:37
 **/
@WebServlet(name = "AddNewsServlet",urlPatterns = {"/AddNewsServlet"},loadOnStartup = 1)
public class AddNewsServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        /* 接收新闻内容，调用相应Service方法处理请求，最终决定跳转到哪个jsp应用 */
        NewsServiceImpl newsService = new NewsServiceImpl();
        NewsDao newsDao = new NewsDaoImpl();
        newsService.setNewsDao(newsDao);

        boolean bRet = false;
        boolean bUpload = false;
        String uploadFileName = "";
        String fieldName = "";
        News news = new News();
        news.setCreateDate(new Date());
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);//当表单是以多部分方式提交的时候为true

        /*
         * request.getSession().getServletContext().getRealPath("/")
         * 是指tomcat下webapps下的项目根路径
         * */
        String uploadFilePath = request.getSession().getServletContext().getRealPath("/upload/");//获取上传图片文件夹路径
        if (isMultipart == true) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> fileItems = null;//将请求对象转换成集合
            try {
                fileItems = upload.parseRequest(request);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()) {//如果是普通字段
                    fieldName = fileItem.getFieldName();
                    if (fieldName.equalsIgnoreCase("title")) {
                        news.setTitle(fileItem.getString("UTF-8"));
                    } else if (fieldName.equalsIgnoreCase("id")) {
                        String id = fileItem.getString();
                        if (StringUtils.isNotBlank(id)) {
                            news.setId(Integer.parseInt(id));
                        }
                    } else if (fieldName.equalsIgnoreCase("categoryId")) {
                        news.setCategoryId(Integer.parseInt(fileItem.getString()));
                    } else if (fieldName.equalsIgnoreCase("summary")) {
                        news.setSummary(fileItem.getString("UTF-8"));
                    } else if (fieldName.equalsIgnoreCase("newscontent")) {
                        news.setContent(fileItem.getString("UTF-8"));
                    } else if (fieldName.equalsIgnoreCase("author")) {
                        news.setAuthor(fileItem.getString("UTF-8"));
                    }
                } else {
                    String fileName = fileItem.getName();
                    if (StringUtils.isNotBlank(fileName)) {
                        File fullFile = new File(fileItem.getName());
                        File saveFile = new File(uploadFilePath, fullFile.getName());

                        try {
                            fileItem.write(saveFile);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        uploadFileName = fullFile.getName();
                        news.setPicPath(uploadFileName);

                        bUpload = true;
                    }
                }
            }
        }
        System.out.println("上传成功后的文件名是：" + news.getPicPath());
        bRet = newsService.addNews(news);

        if (bRet) {
            response.sendRedirect("jsp/admin/newsDetailList.jsp");
        } else {
            response.sendRedirect("jsp/admin/newsDetailCreate.jsp");

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
